package com.example.treehole.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.example.treehole.base.BaseBindingFragment;
import com.example.treehole.base.BindAdapter;
import com.example.treehole.databinding.FragmentWeatherBinding;
import com.example.treehole.databinding.ItemDetailBinding;
import com.example.treehole.util.PreferenceUtil;
import com.example.treehole.util.SomeUtil;
import com.google.gson.Gson;
import com.qweather.sdk.response.indices.IndicesDaily;
import com.qweather.sdk.response.weather.WeatherNow;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class WeatherFragment extends BaseBindingFragment<FragmentWeatherBinding> {

    private BindAdapter<ItemDetailBinding, IndicesDaily> adapter = new BindAdapter<ItemDetailBinding, IndicesDaily>() {
        @Override
        public ItemDetailBinding createHolder(ViewGroup parent) {
            return ItemDetailBinding.inflate(getLayoutInflater(), parent, false);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void bind(ItemDetailBinding item, IndicesDaily data, int position) {
            item.tvName.setText(data.getName());
            item.tvValue.setText(data.getCategory());
            item.tvInfo.setText("解析" + data.getText());
        }
    };
    GeoCoder mCoder;

    @Override
    protected void initData() {
        Bundle arguments = getArguments();
        if (arguments != null) {
            viewBinder.rvLife.setAdapter(adapter);
            String city = arguments.getString("city");
            String provinces = arguments.getString("provinces");
            String latlng = arguments.getString("latLng");
            getWeatherNow(city, latlng);
            getIndices(city, latlng);
        }
    }

    private void getIndices(String city, String latlng) {
        Callback callback = new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    String string = response.body().string();
                    Log.d("callback-", string);
                    try {
                        JSONObject object = new JSONObject(string);
                        JSONArray dailyJson = object.getJSONArray("daily");
                        PreferenceUtil.getInstance().save(city + SomeUtil.getTime() + "Indices", string);
                        adapter.getData().clear();
                        for (int i = 0; i < dailyJson.length(); i++) {
                            JSONObject daily = dailyJson.getJSONObject(i);
                            IndicesDaily indicesDaily = new Gson().fromJson(daily.toString(), IndicesDaily.class);
                            adapter.getData().add(indicesDaily);
                        }
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                adapter.notifyDataSetChanged();
                            }
                        });
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        String cache = PreferenceUtil.getInstance().get(city + SomeUtil.getTime() + "Indices", "");
        if (!cache.isEmpty()) {
            try {
                JSONObject object = new JSONObject(cache);
                Log.d("Cache", cache);
                JSONArray dailyJson = object.getJSONArray("daily");
                adapter.getData().clear();


                for (int i = 0; i < dailyJson.length(); i++) {
                    JSONObject daily = dailyJson.getJSONObject(i);
                    IndicesDaily indicesDaily = new Gson().fromJson(daily.toString(), IndicesDaily.class);
                    adapter.getData().add(indicesDaily);
                }
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        adapter.notifyDataSetChanged();
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return;
        }
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://n43qqkk3w4.re.qweatherapi.com/v7/indices/1d?location=" + latlng + "&type=0")
                .addHeader("X-QW-Api-Key", "a47c6bf981994c04a6dae7c546aa43de")
                .build();
        client.newCall(request).enqueue(callback);
    }

    private void getWeatherNow(String city, String latlng) {
        String cache = PreferenceUtil.getInstance().get(city + SomeUtil.getTime() + "WeatherNow", "");
        if (!cache.isEmpty()) {
            try {
                Log.d("Cache", cache);
                JSONObject jsonObject = new JSONObject(cache);
                JSONObject nowJson = jsonObject.getJSONObject("now");
                WeatherNow now = new Gson().fromJson(nowJson.toString(), WeatherNow.class);
                viewBinder.tvName.setText(now.getText());
                viewBinder.tvValue.setText(now.getTemp());
                viewBinder.tvMax.setText(now.getFeelsLike() + "℃");
                viewBinder.tvHumidity.setText(now.getHumidity());
//                                                viewBinder.tvSunDown.setText(now.getHumidity());
                viewBinder.tvWineLevel.setText(now.getWindSpeed() + "公里/小时");
                viewBinder.tvWindDirection.setText(now.getWindDir());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return;
        }
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://n43qqkk3w4.re.qweatherapi.com/v7/weather/now?location=" + latlng)
                .addHeader("X-QW-Api-Key", "a47c6bf981994c04a6dae7c546aa43de")
                .build();
        client.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e("XXonFailure", e.getLocalizedMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    try {
                        JSONObject jsonObject = new JSONObject(response.body().string());
                        JSONObject nowJson = jsonObject.getJSONObject("now");
                        WeatherNow now = new Gson().fromJson(nowJson.toString(), WeatherNow.class);
                        PreferenceUtil.getInstance().save(city + SomeUtil.getTime() + "WeatherNow", jsonObject.toString());
                        new Handler(Looper.getMainLooper())
                                .post(new Runnable() {
                                    @Override
                                    public void run() {
                                        viewBinder.tvName.setText(now.getText());
                                        viewBinder.tvValue.setText(now.getTemp());
                                        viewBinder.tvMax.setText(now.getFeelsLike() + "℃");
                                        viewBinder.tvHumidity.setText(now.getHumidity());
//                                                viewBinder.tvSunDown.setText(now.getHumidity());
                                        viewBinder.tvWineLevel.setText(now.getWindSpeed() + "公里/小时");
                                        viewBinder.tvWindDirection.setText(now.getWindDir());
                                    }
                                });
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    @Override
    protected void initListener() {

    }
}
